﻿namespace Sai.Cecil
{
	using System;
	using System.Collections.Generic;
	using Mono.Cecil;

	/// <summary>
	/// Factory type extension to build a declarations from equivalent mono definition objects.
	/// </summary>
	public static class GenericInstanceTypeExtensions
	{
		/// <summary>
		/// Creates a familiar template type name from a generic instance name 
		/// e.g. Given List'1 will return List&lt;T&gt;.
		/// </summary>
		/// <param name="git">The generic type.</param>
		/// <returns>The full name of the type with arguments in angle brackets.</returns>
		public static string GenericTypeName(this GenericInstanceType git)
		{
			if (git.IsGenericInstance)
			{
				return string.Format(
					"{0}<{1}>",
					git.Name.NonGenericName(),
					string.Join(",", git.GenericArguments()));
			}

			return git.Name;
		}

		/// <summary>
		/// Creates a list of generic arguments from generic instance type.
		/// </summary>
		/// <param name="git">The generic type.</param>
		/// <returns>A list of arguments.</returns>
		private static IEnumerable<string> GenericArguments(this GenericInstanceType git)
		{
			var genericArgs = new List<string>();

			int count = git.GenericArguments.Count;

			if (count > 0)
			{
				foreach (var param in git.GenericArguments)
				{
					genericArgs.Add(param.Name);
				}
			}

			return genericArgs;
		}
	}
}
